/**
 * weapp-js v1.7.1(2021-4-16)
 * https://codeup.aliyun.com/motigo/motigo/weapp_base
 * Copyright@ 2021 Motigo, Inc.
 * 
 */
import BaseRequest from './base_request.js';

export default {
    /* stat: 数据统计
      - 参数:
        - key: 要上报的信息名字
        - elapsed_time: 耗时，单位秒, 如果不需要统计耗时，可以不填
      - 示例：
      ```
        mox.stat('booking_switch_date');
        mox.stat('booking_refresh_data', delta_time);
      ```
     */
    appid: '',
    _statBuf: [],
    _statTimer: null,
    init(opts) {
        this.appid = opts.appid;
    },
    stat(key, elapsed_time) {
        this._statBuf.push({
            key: key,
            elapsed_time: elapsed_time
        });

        if(this._statTimer) {
            clearTimeout(this._statTimer);
        }

        this._statTimer = setTimeout(()=>{
            try {
                let pvuvData = [];
                this._statBuf.forEach(item=>{
                    pvuvData.push({
                        key: item.key,
                        elapsed_time: item.elapsed_time || 0
                    })
                })

                if (pvuvData.length) {
                    BaseRequest.post(`/data/pvuv/weapp_${this.appid}`, pvuvData).then().catch(()=>{});
                }
                this._statBuf = [];
            } catch(e) {
                console.error('exception when report monitor data, err:', e);
            }
        }, 5000);
    }
}